<template>
  <Dialog
    ref="refDialog"
    :title="state.title"
    width="500"
    draggable
    :hasFooter="false"
    @clickClose="onClickClose"
  >
    <div class="text-center relative pb-4">
      <div ref="refBoxLoading" class="border-qrcode">
        <div ref="" class="w-[200px] h-[200px] mx-auto relative">
          <img
            class="object-contain w-full h-full"
            :class="{ 'opacity-0': !style.isReady }"
            :src="format.base64ToImageSrc(qrCode.qrCodeImageBase64)"
          />
          <template v-if="props.purpose == 'sealAdd'">
            <div
              class="status-desc"
              v-show="[1, 2, 4].includes(+style.scannedStatus)"
            >
              <div v-show="style.scannedStatus == 1">
                <div>
                  <img src="./images/icon-success.svg" alt="" />
                </div>
                <div class="mt-1">
                  <p class="text-[#323335]">已扫码</p>
                  <p class="text-[#969AA0]">请在APP中选择证书</p>
                </div>
              </div>
              <div v-show="style.scannedStatus == 2">
                <img
                  @click="loadQrCode"
                  class="cursor-pointer"
                  src="./images/icon-refresh.svg"
                  alt=""
                />
                <div class="mt-1">二维码已失效</div>
              </div>
              <div v-show="style.scannedStatus == 4">
                <img
                  @click="loadQrCode"
                  class="cursor-pointer"
                  src="./images/icon-refresh.svg"
                  alt=""
                />
                <div class="mt-1">手机端应用程序已退出</div>
              </div>
            </div>
          </template>
          <template v-else>
            <div
              class="status-desc"
              v-show="[2].includes(+style.scannedStatus)"
            >
              <div
                @click="loadQrCode"
                v-show="style.scannedStatus == 2"
                class="cursor-pointer"
              >
                <img src="./images/icon-refresh.svg" alt="" />
                <div class="text-primary mt-1">二维码已失效</div>
              </div>
            </div>
          </template>
        </div>
        <div
          class="mt-5 text-[#323335]"
          v-if="qrCode.hyperLinkText"
          v-html="qrCode.hyperLinkText"
        ></div>
        <div class="text-[#64666B] leading-[22px]">
          <div v-show="[0, 1].includes(+style.scannedStatus)">
            二维码将在<span class="mx-1 text-primary"
              ><TickDown ref="refTickDown" @end="onInvalid" /></span
            >后失效
          </div>
          <div v-show="style.scannedStatus == 2">
            二维码失效<span
              class="text-primary mx-1 cursor-pointer"
              @click="loadQrCode"
              >刷新获取</span
            >
          </div>
          <div v-show="style.scannedStatus == 4">
            应用程序已退出<span
              class="text-primary mx-1 cursor-pointer"
              @click="loadQrCode"
              >重新获取二维码</span
            >
            签章
          </div>
        </div>
      </div>
    </div>
  </Dialog>
</template>
<script setup>
import { reactive, toRefs, ref, nextTick, inject } from "vue";
import { http, format, toast, ss, loading } from "@/utils";
import _ from "lodash";
import TickDown from "@/components/ui/TickDown.vue";

const provideHome = inject("provideHome");
const refDialog = ref();
const refBoxLoading = ref();
const refTickDown = ref();

const props = defineProps({
  purpose: {
    type: String, //sealAdd 加章、sealRemove 撤章
    required: false,
    default: "sealAdd",
  },
});

const emits = defineEmits(["submit"]);

const state = reactive({
  title: "",
  restTime: "",
  style: {
    isReady: false,
    /** dialog窗口是否显示  */
    visible: false,
    /** 扫码状态 */
    scannedStatus: "",
  },
  polling: {
    timerId: "",
  },
  qrCode: {
    tid: "",
    qrCodeImageBase64: "",
    qrCodeJumpUrl: "",
    hyperLinkText: "",
  },
});

const { qrCode, style } = toRefs(state);

const loadQrCode = async () => {
  state.style.isReady = false;
  state.style.scannedStatus = -1;
  let params = {};
  if (props.purpose == "sealAdd") {
    params = {
      serviceCode: "electronicSealSignature",
      featureCode: "getElectronicSealSignatureQRCode",
    };
  } else {
    params = {
      serviceCode: "revokeElectronicSealSignature",
      featureCode: "getRevokeElectronicSealSignatureQRCode",
      businessData: {
        fileId: ss.get("fileId"),
      },
    };
  }

  loading.show({
    target: refBoxLoading.value,
    background: "rgba(0,0,0,0)",
    text: "",
  });

  // console.log("loading target", refBoxLoading.value);
  const [err, res] = await http.post({
    // showLoading: refBoxLoading.value,
    data: params,
  });
  loading.close();
  if (res) {
    _.assign(state.qrCode, res);
    pollingStart();

    refTickDown.value.reset();
    state.style.isReady = true;
  } else {
    onClose();
  }
};

const onInvalid = () => {
  state.style.scannedStatus = 2;
  pollingStop();
  console.log("二维码已失效...");
};

/** 轮询扫码状态 */
const pollingStart = () => {
  let serviceCode, featureCode;
  if (props.purpose == "sealAdd") {
    serviceCode = "electronicSealSignature";
    featureCode = "getQRCodeScanStatus";
  } else {
    serviceCode = "revokeElectronicSealSignature";
    featureCode = "getQRCodeScannedStatus";
  }

  const _doPoll = async () => {
    if (!state.style.visible) {
      //弹窗未展示时，停止执行
      return;
    }
    const [err, res] = await http.post({
      data: {
        serviceCode,
        featureCode,
        businessData: {
          tid: state.qrCode.tid,
        },
      },
    });
    if (res) {
      if (!state.style.visible) {
        //当前弹窗未处于显示状态，不响应接口返回
        return;
      }
      let { scannedStatus, scannedDesc } = res;
      state.style.scannedStatus = scannedStatus;
      if (scannedStatus == 0) {
        //00 未扫码
        state.timerId = setTimeout(_doPoll, 2000);
      } else if (scannedStatus == 1) {
        //01 已扫码未授权
        state.timerId = setTimeout(_doPoll, 2000);
      } else if (scannedStatus == 2) {
        //02 已失效
        onInvalid();
        // toast.warning("二维码失效，已重新生成。");
        // pollingStop();
        // loadQrCode();
      } else if (scannedStatus == 3) {
        // 03 已扫码已授权
        // toast.success(scannedDesc);
        pollingStop();
        emits("submit");
      } else if (scannedStatus == 4) {
        // 04 已退出
        pollingStop();
      }
    } else {
      onClose();
    }
  };
  _doPoll();
};

const onReset = () => {
  state.qrCode = {
    tid: "",
    qrCodeImageBase64: "",
    qrCodeJumpUrl: "",
    hyperLinkText: "",
  };
};

/** 结束轮询 */
const pollingStop = () => {
  // console.log("停止扫码二维码的轮询");
  clearTimeout(state.timerId);
};

const onShow = ({ title = "扫码签章" } = {}) => {
  state.title = title;
  state.style.visible = true;
  refDialog.value.show();
  onReset();
  nextTick(() => {
    //为了showLoading生效，用 nextTick 包一下
    loadQrCode();
  });
};

const onClickClose = () => {
  onClose();
  seal.exitAppLinkWhenSealAdd();
  provideHome.methods.setSealCurrentOperateName("");
};

const onClose = () => {
  state.style.visible = false;
  pollingStop();
  refDialog.value.close();
};

defineExpose({
  show: onShow,
  close: onClose,
});
</script>
<style lang="scss">
.status-desc {
  @apply absolute inset-0 bg-[rgba(255,255,255,.95)] flex items-center justify-center text-[#323335] text-center;
}
.border-qrcode {
  // @apply w-[240px] h-[240px] z-10 pointer-events-none;
  background: url(./images/border-qrcode.png) no-repeat;
  background-size: contain;
  @apply pt-[30px] mt-[20px] mx-auto w-[280px];
}
</style>
